package zwp.exercise.intereview.base.sort;

import java.util.Arrays;

/**
 * @Author zwp14
 * @create 2024/6/28 11:35
 * @description 冒泡排序复习1
 */
public class BubbleSortReview1 {
    public static void main(String[] args) {
        //定义数组
        int[] array = {5, 9, 7, 4, 1, 3, 2, 8};


        bestMethod(array);
        batterMethod(array);
    }

    private static void bestMethod(int[] array) {
        //
        int maxIdx = array.length - 1;
        for (; ; ) {
            //last做为标记存在,初始为0,如果第一次就没有发生交换,则能够直接终止循环排序
            int last = 0;
            for (int j = 0; j < maxIdx; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    last = j;
                }
            }
            //last之后的索引已经有序,无序再进行比较排序
            maxIdx = last;
            if (maxIdx == 0) {
                break;
            }
            System.out.println(Arrays.toString(array));
        }
    }

    private static void batterMethod(int[] array) {
        //定义轮次
        for (int i = 0; i < array.length - 1; i++) {
            boolean isExchange = false;
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    isExchange = true;
                }
            }
            if (!isExchange) {
                break;
            }
            System.out.println(Arrays.toString(array));
        }
    }
}
